#pragma once
#include "logMessage.hpp"
// #include "Task.hpp"
#include "ThreadPool.hpp"

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
using namespace std;

namespace Server
{
    enum
    {
        SOCKET_ERR = 1,
        BIND_ERR,
        LISTEN_ERR,
        ACCEPT_ERR,
        USAGE_ERR,
    };
    static const uint16_t gPort = 8080;
    static const int gbacklog = 5;
    class TcpServer;
    class ThreadDate
    {
    public:
        ThreadDate(TcpServer *self, const int &sock)
            : _self(self), _sock(sock)
        {
        }

    public:
        TcpServer *_self;
        int _sock;
    };

    class TcpServer
    {
    public:
        TcpServer(const uint16_t &port = gPort)
            : _listensock(-1), _port(port)
        {
        }
        ~TcpServer()
        {
        }

        void InitTcpServer()
        {
            // 1.创建套接字 面向字节流
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "Create Socket Fail!");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "Create Socket Success!");

            // 2.bind
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            peer.sin_addr.s_addr = INADDR_ANY; // IP地址绑定任意的
            peer.sin_family = AF_INET;
            peer.sin_port = htons(_port);

            if (bind(_listensock, (struct sockaddr *)&peer, sizeof(peer)) < 0)
            {
                logMessage(FATAL, "Bind Socket Fail!");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "Bind Socket Success!");

            // 3.Socket 设置为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                // 设置失败
                logMessage(FATAL, "Listen Socket Fail!");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "Listen Socket Success!");
        }
        void Start()
        {
            // signal(SIGCHLD,SIG_IGN);

            // 使线程池跑起来
            // ThreadPool<Task>::getInstance()->Thread_Work();
            // logMessage(NORMAL, "Create ThreadPool Success!");
            // Todo
            //  4.Socket获取新链接，返回值是一个新的文件fd，(每一个链接都会产生新的fd)
            while (1)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(FATAL, "Accept Socket Fail!");
                    exit(ACCEPT_ERR);
                }
                logMessage(NORMAL, "Accpet Socket Success!");
                cout << "new sock# " << sock << endl;

                // 5.对 sock进行 IO操作  只能是串行，单进程执行 version 1
                // ServerIO(sock);
                // close(sock);//关闭fd

                // 多进程版  version 2
                // 交给子进程进行处理
                pid_t pid = fork();
                if (pid == 0) // child
                {
                    // 子进程会继承父进程的fd  close不需要的
                    close(_listensock);
                    // version 2.1
                    // 采用忽略掉子进程发送信号的方式

                    // 让孙子进程处理，父进程waitpid,OS会回收
                    //  if(fork() > 0)
                    //  {
                    //      exit(0);
                    //  }
                    ServerIO(sock);
                    close(sock);
                    exit(0); // 孤儿进程
                }
                // parent  回收子进程
                close(sock);
                // pid_t n = waitpid(pid, nullptr, 0); // 第二个参数是要保存子进程的状态  返回值是进程的pid
                // if (n > 0)
                // {
                //     cout << "waitpid success ... !  n#-> " << n << endl;
                // }

                // 多线程版  version 3
                pthread_t tid;
                ThreadDate *td = new ThreadDate(this, sock);
                // 需要把this,与sock转递给回调函数
                pthread_create(&tid, nullptr, routine, td);
                // pthread_join(tid, nullptr);

                // 线程池版  version 4
                // ThreadPool<Task>::getInstance()->Push(Task(sock, ServerIO));
            }
        }

        void ServerIO(int sock)
        {
            char buffer[1024];
            while (true)
            {
                ssize_t n = read(sock, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    buffer[n] = 0;
                    // 读取成功
                    cout << "recv message: " << buffer << endl;

                    string msg = "[server responess]: ";
                    msg += buffer;
                    write(sock, msg.c_str(), msg.size());
                }
                else if (n == 0)
                {
                    // 代表客户端退出
                    logMessage(NORMAL, "Client Already Exit,Me too!");
                    break;
                }
                // 线程跑完close
                //close(sock);
            }
        }

        static void *routine(void *args)
        {
            // 避免串行，进程线程分离
            pthread_detach(pthread_self());
            ThreadDate *td = static_cast<ThreadDate *>(args);
            td->_self->ServerIO(td->_sock);
            close(td->_sock);
            delete td;
            return nullptr;
        }

    private:
        int _listensock;
        uint16_t _port;
    };
}